import os.path
from django.core.files import File
from django.conf import settings
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from timelineapp.forms import TimelineForm
from timelineapp.models import Timeline, TimelineCategory
from crowdTimeline.utils.CustomSerializer import JSONSerializer
from eventapp.models import Asset, Event
from permissionapp.models import Permission
from permissionapp.views import set_permission, send_invitation
from django.contrib.auth.models import User
from django.http import Http404
from random import choice

def json_response_from(response):
    jsonSerializer = JSONSerializer()
    return HttpResponse(jsonSerializer.serialize(response, use_natural_keys=True), mimetype='application/json')

def get_timeline_json(timeline):
    response = {}
    
    # json fields
    timeline_values = ["headline", "description"]
    event_values = ["headline", "text", "startDate"]
    asset_values = ["media", "caption", "credit"]
        
    timeline_dict = timeline.toDict(timeline_values)
    timeline_dict["type"] = "default"
    
    if (timeline.initial_date):
        timeline_dict["startDate"] = timeline.initial_date
        
    # Gets approved timeline events
    events_qs = Event.objects.filter(timeline=timeline.id).filter(approved=1)
    
    timeline_events = []
    for e in events_qs:
        # Get approved event assets
        event_assets = Asset.objects.filter(event=e.id).filter(approved=1)
        for a in event_assets:
            e_dict = e.toDict(event_values)
            e_dict["asset"] = a.toDict(asset_values)
            timeline_events.append(e_dict)
    
    timeline_dict["date"] = timeline_events
    response.update({"timeline": timeline_dict})
    
    timeline_json = json_response_from(response)
    json_name = "timeline%s.json" % (timeline.id)
    
    # Saves json to file
    os.chdir(os.path.join(os.path.dirname(__file__), "static", "temp"))             
    f = open(json_name, 'w')
    myFile = File(f)
    myFile.writelines(timeline_json)
    myFile.close()
    f.close()
    
    json_complete_path = os.path.join(settings.STATIC_URL, "temp", json_name).replace('\\','/')
    return json_complete_path
    
def get_timeline_info(request, timeline_id):
    timeline = {}
    if not timeline_id:
        timeline.title = 'Timeline Inexistente.'
    else:
        timeline = Timeline.objects.get(pk=timeline_id)

        if (timeline.initial_date):
            timeline.initial_date = timeline.initial_date.strftime("%d/%m/%Y")
        
        if not timeline.creator_id:
            creator = ""
        else:
            creator = timeline.creator.email
        
        events = Event.objects.filter(timeline=timeline_id)
        number_of_events = events.count() - 1 # Removing folder
        
    return (timeline, creator, number_of_events)

def home(request):
    all_timelines = Timeline.objects.all()        
    timelines = [] #Displays two timelines randomly chosen.

    if (len(all_timelines)):    
        first = choice(all_timelines)
        timelines.append(first)
    
    if (len(all_timelines) > 1):
        second = choice(all_timelines)
        while (second == first):
            second = choice(all_timelines)
        timelines.append(second)

    return render_to_response('home.html', {"timelines" : timelines, 
                                            "count" : all_timelines.count(), 
                                            "members": User.objects.all().count()} )

def get_emails(form):
    emails_string = form.cleaned_data['invitations']
    email_list = emails_string.split(',') 
    return email_list

def create_timeline(request):
    # There must be a logged user to perform this action
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login?previous=/timelines/new')

    action = "Add"
    if request.method == 'POST':
        form = TimelineForm(request.POST)
        if form.is_valid():
            timeline = form.save(request)
            emails = []
            emails = get_emails(form)
            if form.cleaned_data['private'] == True:
                emails.append(request.user.username)
                set_permission(emails, timeline)
                emails.pop()
            if emails[0]!='' or len(emails)>1:
                send_invitation(emails, timeline)
            
            events_count = Event.objects.all().count()
            cover_count = Timeline.objects.filter(cover__isnull=False)
            events_count = events_count - cover_count 
            if (events_count > 0):
                return HttpResponseRedirect('/timelines/%d/import_events' % timeline.id)
            else:
                return HttpResponseRedirect('/timelines/%d' % timeline.id)
    else:
        form = TimelineForm()
           
    return render_to_response('timeline_form.html', {'form':form, "action":action})

def list_timelines(request):
    action = "list"
    category =  TimelineCategory.objects.order_by('name')
    selected_category = 0
    timelines = []
    
    if request.method == 'GET':
        if ("timeline_category" in request.GET):
            selected_category = int(request.GET["timeline_category"]) 
    
    if not selected_category:
    
        timelines_list = Timeline.objects.all()
        for t in timelines_list:
            if t.privacy==True:
                try:
                    if request.user.is_authenticated():
                        permission = Permission.objects.get(user=request.user, timeline=t)
                        timelines.append(t)
                except Permission.DoesNotExist:
                    pass
            else:
                timelines.append(t)
        
    else:
        timelines_list = Timeline.objects.filter(categories = selected_category)
        for t in timelines_list:
            if t.privacy==True:
                try:
                    if request.user.is_authenticated():
                        permission = Permission.objects.get(user=request.user, timeline=t)
                        timelines.append(t)
                except Permission.DoesNotExist:
                    pass
            else:
                timelines.append(t)
        
    return render_to_response('timelines.html', locals())

def show_timeline(request, timeline_id):
    try:
        t = Timeline.objects.get(id=timeline_id)
        if t.privacy==True:
            if not request.user.is_authenticated():
                return HttpResponseRedirect('/user/login?previous=/timelines/%s'% timeline_id)
            try:
                permission = Permission.objects.get(user=request.user, timeline=t)
            except Permission.DoesNotExist:
                raise Exception("Voce nao tem autorizacao para acessar esta Timeline.")
    except Timeline.DoesNotExist:
        raise Http404
    
    (timeline, creator, number_of_events) = get_timeline_info(request, timeline_id)
    
    timeline_json = get_timeline_json(timeline)
    return render_to_response('timeline.html', {"timeline" : timeline,
                                                "timeline_id" : timeline_id, 
                                                 "creator" : creator,
                                                 "json" : timeline_json,
                                                 "number_of_events": number_of_events})

def edit_timeline(request, timeline_id):
    action = "Edit"
    
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login?previous=/timelines/%s/edit' % timeline_id)
    
    try:
        t = Timeline.objects.get(id=timeline_id)
        if t.privacy==True:
            try:
                permission = Permission.objects.get(user=request.user, timeline=t)
            except Permission.DoesNotExist:
                raise Exception("Voce nao tem autorizacao para acessar esta Timeline.")
    except Timeline.DoesNotExist:
        raise Http404
    
    (timeline, creator, number_of_events) = get_timeline_info(request, timeline_id)
    cover = Asset.objects.get(pk=timeline.cover.id)
    event = Event.objects.get(pk=timeline.cover.id)
    
    if request.method == 'POST':
        form = TimelineForm(request.POST, None)
        if form.is_valid():
            cd = form.cleaned_data
            timeline.title = cd["title"]
            timeline.description = cd["description"]
            timeline.initial_date = cd["initial_date"]
            timeline.final_date = cd["final_date"]
            #Only a private timeline can become public, 
            # but a public timeline can not become private
            if timeline.privacy==1:
                timeline.privacy = cd['private']
            timeline.save()
            
            event.title = cd["title"]
            event.description = cd["description"]
            event.save()
            
            cover.media = cd["cover"]
            cover.caption = cd["caption"]
            cover.credit = cd["credit"]
            cover.save()
            
            emails = []
            emails = get_emails(form)
            if cd['private'] == True:
                emails.append(request.user.username)
                emails.pop()
            if emails[0]!='' or len(emails)>1:
                print "emails: ",emails
                print "len(emails): ",len(emails)
                send_invitation(emails, timeline)
            
            return HttpResponseRedirect('/timelines/%s' % timeline_id)
    else:
        form = TimelineForm()
           
    return render_to_response('timeline_form.html', {"timeline" : timeline, 
                                                     "action" : action, 
                                                     "timeline_id" : timeline_id,
                                                     "form" : form,
                                                    "creator": creator,
                                                    "number_of_events" : number_of_events,
                                                    "cover" : cover})

def delete_timeline(request, timeline_id):
    timeline_title = "Delete Timeline %s" % timeline_id
    return render_to_response('timeline.html', locals())

def import_events(request, timeline_id):
    # There must be a logged user to perform this action
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/user/login?previous=/timelines/%s/import_events' % timeline_id)
    
    try:
        t = Timeline.objects.get(id=timeline_id)
        if t.privacy==True:
            try:
                permission = Permission.objects.get(user=request.user, timeline=t)
            except Permission.DoesNotExist:
                raise Exception("Voce nao tem autorizacao para acessar esta Timeline.")
    except Timeline.DoesNotExist:
        raise Http404

    action = "select"
    groups = []
    category =  TimelineCategory.objects.all()
    selected_category = 0
    timeline = Timeline.objects.get(pk=timeline_id)

    if request.method == 'POST':
        
        # Gets event from request and adds to the timeline
        if "events" in request.POST:
            for i in request.POST.getlist("events"):
                event = Event.objects.get(pk=i)
                timeline.events.add(event)
            
            timeline.save()
        return HttpResponseRedirect('/timelines/%s' % timeline_id)
        
    elif request.method == 'GET':
        # Selects the category of timelines to be displayed.
        if ("timeline_category" in request.GET):
            selected_category = int(request.GET["timeline_category"]) 
    
        # Retrieves timelines events
        elif ("timelines" in request.GET):
            action = "import"
            events = []
            
            for i in request.GET.getlist("timelines"):
                d = {}
                d["timeline"] = Timeline.objects.get(pk=i)
                d["events"] = []
                events = Event.objects.filter(timeline=i)
                for e in events:
                    d["events"].append(e)
                groups.append(d)
                    
    if not selected_category:
        timelines = Timeline.objects.exclude(id = timeline_id)
    else:
        timelines = Timeline.objects.filter(categories = selected_category)

    return render_to_response('timelines.html', locals())
